import {size} from '@/utils/size'
import {itemData} from "@/utils/itemData";
import {translateZhToEn, translateLaosToEn, translateLaosToZh, translateZhToLaos} from "@/utils/translate";
import {getUsableApi, updateExpressOrderHaveSonApi} from '@/api/order'
import {checkPriceApi} from "@/api/operation";
import {getSenderApi} from "@/api/website/inform";
import {isEmpty} from "@/utils/common";

export default {
  data() {
    return {
      // 提交按钮
      hasSubmit: true,
      // 单号余量
      leftNumber: 0,
      // 子单
      son: {
        hasSon: false,
        packTotal: 0,
        total: 0,
        childrenList: [{length: 0, width: 0, height: 0, packWay: '无包装', count: 1, key: 0}]
      },
      // 规格型号
      specification: '',
      // 选择物品
      selectItem: [],
      // 品牌
      brand: '无品牌',
      brandOption: [],
      // 尺寸
      sizeList: [],
      // 计算体积重量
      computeWeight: {
        length: 0, width: 0, height: 0
      },
      // 包装类型
      packOptions: [
        {key: 1, value: '无包装', label: '无包装'},
        {key: 2, value: '木箱', label: '木箱'},
        {key: 3, value: '纸箱', label: '纸箱'},
        {key: 4, value: '编织袋', label: '编织袋'},
        {key: 5, value: '塑料袋', label: '塑料袋'},
        {key: 6, value: '木架', label: '木架'},
        {key: 7, value: '木托', label: '木托'},
        {key: 8, value: '其他', label: '其他'}
      ]
    }
  },
  computed: {
    itemData() {
      return itemData
    },
    size() {
      return size
    },
    isRMB() {
      return this.$storeGet.setting.isRMB
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    // 提交
    submit() {
      if (this.form.weight === 0 || this.form.freight === 0 && this.form.websiteClearingWay === 1) {
        this.$errorMsg('重量或运费为0，无法提交。');
        return
      }
      let data = {...this.form};
      if (this.son.hasSon) data.jsonList = JSON.stringify(this.son.childrenList) // 子单
      if (!isEmpty(this.$storeGet.order)) { // 在线下单
        data.mailId = this.$storeGet.order.id
        data.com = this.$storeGet.order.com
        data.otherNumber = this.$storeGet.order.number
      }
      data.freight = this.roundNumber(data.freight) // 运费向上取整
      if (this.brand !== '无品牌') {  // 品牌
        data.goods = this.brand
      } else {
        data.goods = ''
      }
      this.$refs['Form'].validate(valid => {
        if (!valid) {
          this.$errorMsg('无法提交，有必填项未填写');
          return;
        }
        this.$msgBox('确认提交？').then(() => {
            this.$refs.Submit.start();
            this.$startLoading();
            updateExpressOrderHaveSonApi(data).then(result => {
              this.$refs.Submit.stop();
              this.$stopLoading();
              if (result.status !== 200) return;
              this.print()
              this.cancel()
            }).catch(() => {
              this.$refs.Submit.stop();
              this.$stopLoading();
            });
          }
        )
      })
    },

    // 获得网点各种信息
    getInfo() {
      if (this.$special) { // 特殊账号
        checkPriceApi().then(result => {
          // 余额低于警戒线
          if (result.resultParam.isWarning) {
            this.hasSubmit = false;
            this.$warnMsg('余额低于警戒线，无法提交')
          }
        })
      } else { // 普通账号
        getUsableApi().then(result => {
          let response = result.resultParam;
          // 资金低于警戒线
          if (response.isPriceWarning) {
            this.hasSubmit = false;
            this.$warnMsg('资金低于警戒线，无法进行揽收')
            return
          }
          // 单号低于警戒线
          if (response.isNumberWarning) {
            this.$warnMsg('单号低于警戒线')
          }
          // 单号和单号余量
          this.form.number = response.expressOrder.number;
          this.leftNumber = response.count
        })
      }
    },

    // 选择品名
    changeItemName() {
      this.form.articleName = '';
      this.$nextTick(() => {
        let node = this.$refs.ItemCascader.getCheckedNodes();
        if (node.length === 0) {
          this.form.articleName = ''; // 品名
          this.form.laosArticleName = '';
          this.form.enArticleName = '';
          this.form.dutyParagraph = ''; // 税号
          this.form.specification = ''; // 规格
          this.form.insideCount = 1; // 内件数量
          this.form.declarationUnitFee = 0; // 申报单价
          this.form.declarationTotalFee = 0; // 申报总价
          this.form.taxRate = 0; // 税率
          this.form.receivableTax = 0; // 应收税额
          this.form.realTax = 0; // 实收税额
          this.form.repairTax = 0; // 补收税额
          this.form.detailNotes = ''; // 备注(内件明细)
          this.brand = '无品牌';
          this.brandOption = [];
          this.sizeList = [];
          return;
        }
        let data = node[0].data;
        this.form.articleName = data.name; // 品名(中文)
        this.translateZhToLaos(data.name, 'laosArticleName') // 品名(老挝)
        this.translateZhToEn(data.name, 'enArticleName') // 品名(英文)
        this.form.dutyParagraph = data.id; // 税号
        this.form.taxRate = data.tax.replace(/([0-9.]+)%/, (a, b) => +b / 100) // 税率
        this.form.declarationUnitFee = data.price; // 申报单价
        this.getSpecifications(); // 规格型号
        this.$refs.SearchSelectItem.setItemMethod(data.name) // 初始化品名组件
      })
    },

    // 规格型号
    getSpecifications() {
      let number = 0;
      let sizeString = '';
      this.sizeList.forEach(item => { // 计算码数
        sizeString += `${item.name} * ${item.number}件 | `
        number += item.number
      })
      sizeString = sizeString.substring(0, sizeString.length - 3)
      if (number !== 0) { // 计算数量
        this.form.insideCount = number;
      }
      if (this.sizeList.length > 0) { // 规格型号
        this.form.specification = `${this.form.articleName} | ${this.brand} | ${sizeString}`;
      } else {
        this.form.specification = `${this.form.articleName} | ${this.brand} ${'| ' + this.specification + ' '} * ${this.form.insideCount}件`;
      }
      this.form.detailNotes = this.form.specification; // 备注（内件明细）
      this.form.declarationTotalFee = this.form.insideCount * this.form.declarationUnitFee; // 申报总价
      this.form.receivableTax = this.form.declarationTotalFee * this.form.taxRate; // 应收税额

      if (isNaN(this.form.declarationTotalFee)) this.form.declarationTotalFee = 0
      if (isNaN(this.form.receivableTax)) this.form.receivableTax = 0
    },
    changeSpecifications() {
      this.form.detailNotes = this.form.specification;
    },

    /* 计算毛重和净重 */
    changeWeight() {
      this.form.roughWeight = this.form.weight;  // 毛重KG
      this.form.netWeight = this.form.weight * 0.9;  // 净重KG
      this.form.insideRoughWeight = this.form.weight;  // 内件毛重
    },

    /* 添加删除尺寸 */
    addSize(name) {
      let flag = this.sizeList.some(item => {
        if (item.name === name) {
          item.number++
          return true
        }
      })
      if (!flag) {
        this.sizeList.push({name: name, number: 1})
      }
      this.getSpecifications()
    },
    delSize(name) {
      this.sizeList.some((item, index) => {
        if (item.name === name) {
          if (item.number > 1) {
            item.number--
          } else {
            this.sizeList.splice(index, 1)
          }
        }
      })
      this.getSpecifications()
    },

    // 获取一条发件人信息
    getOneSender() {
      getSenderApi().then(result => {
        let response = result.resultParam.sender
        this.form.senderName = response.name; // 寄件人姓名
        this.translateZhToEn(response.name, 'laosSenderName', 'enSenderName'); // 寄件人姓名
        this.form.senderAddress = response.address; // 寄件人详细地址
        this.form.laosSenderAddress = ' '; // 老挝寄件人详细地址
        this.translateZhToEn(response.address, 'enSenderAddress'); // 英文寄件人详细地址
        this.form.beginPlace = response.city; // 始发地
        this.form.laosBeginPlace = ' '; // 始发地
        this.form.senderCity = response.city; // 发件人城市
        this.translateZhToEn(response.city, 'enSenderCity');
        this.form.saleCity = response.city; // 产销城市
        this.form.senderPhone = response.phone; // 寄件人联系电话
        this.form.senderId = response.idCard; // 寄件人证件号
      })
    },

    // 普通/易碎品 ---- 保额/保价费
    changeProtect() {
      if (this.form.isProtect === 0) {
        this.form.protectWay = 0;
        this.form.coverage = 0;
        this.form.protectFee = 0;
        return
      }
      if (this.form.protectWay === 1) {
        this.form.protectFee = this.form.coverage * 0.3
      }
      if (this.form.protectWay === 0) {
        this.form.protectFee = this.form.coverage * 0.03
      }
    },

    // 报关费
    changeIsCustoms(value) {
      if (value === 0) this.form.customsFee = 0;
    },

    // 结算方式
    changeClearingWay(value) {
      if (value === 0) this.form.freight = 0
    },

    // 翻译 中 -> 英
    translateZhToEn(query, ...argument) {
      translateZhToEn(query).then(result => {
        argument.forEach(key => {
          if (Object.prototype.hasOwnProperty.call(this.form, key))
            this.form[key] = result
        })
      })
    },
    // 翻译 中 -> 老
    translateZhToLaos(query, ...argument) {
      translateZhToLaos(query).then(result => {
        argument.forEach(key => {
          if (Object.prototype.hasOwnProperty.call(this.form, key))
            this.form[key] = result
        })
      })
    },
    // 翻译 老 -> 中
    translateLaosToZh(query, ...argument) {
      translateLaosToZh(query).then(result => {
        argument.forEach(key => {
          if (Object.prototype.hasOwnProperty.call(this.form, key))
            this.form[key] = result
        })
      })
    },
    // 翻译 老 -> 英
    translateLaosToEn(query, ...argument) {
      translateLaosToEn(query).then(result => {
        argument.forEach(key => {
          if (Object.prototype.hasOwnProperty.call(this.form, key))
            this.form[key] = result
        })
      })
    },
    // 翻译 老 -> 中 英
    translateZhAndEn() {
      this.translateLaosToZh(this.form.laosArticleName, 'articleName')
      this.translateLaosToEn(this.form.laosArticleName, 'enArticleName')
    },

    // 子单
    changeNumber(value) {
      this.son.childrenList = [];
      for (let i = 0; i < value; i++) {
        this.son.childrenList.push({
          length: 0,
          width: 0,
          height: 0,
          packWay: '无包装',
          count: 1,
          key: i
        })
      }
      this.changeTotal()
    },
    changeTotal() {
      let number = 0;
      this.son.childrenList.forEach(item => {
        if (!item.count) item.count = 1;
        number += item.count
      });
      this.son.total = number
      this.calculate();
    },

    // 选择发往网点
    getSite(obj) {
      if (obj) {
        this.form.sendToUserName = obj.username;
        this.form.sendToName = obj.name;
        this.form.laosSendToName = obj.laosName;
      } else {
        this.form.sendToUserName = '';
        this.form.sendToName = '';
        this.form.laosSendToName = '';
      }
    },

    // 计算体积重量
    calculate() {
      let number = 0;
      if (this.son.childrenList.length > 0) {
        this.son.childrenList.forEach(item => {
          if (!item.length) item.length = 0;
          if (!item.width) item.width = 0;
          if (!item.height) item.height = 0;
          if (!item.count) item.count = 1;
          number += item.length * item.width * item.height * item.count
        });
      }
      if (!this.computeWeight.length) this.computeWeight.length = 0;
      if (!this.computeWeight.width) this.computeWeight.width = 0;
      if (!this.computeWeight.height) this.computeWeight.height = 0;
      let num = this.computeWeight.length * this.computeWeight.width * this.computeWeight.height;
      this.form.weight = (num + number) / this.$volume;
      this.changeWeight()
    },

    // 向上取整1000
    roundNumber(num) {
      if (num === 0) return 0
      const number = 1000
      if (num >= number) {
        let temp = num % number; // 取余
        if (temp !== 0) {
          num = num - temp + number
        }
      } else {
        num = number;
      }
      return num
    },

    // 打印
    print() {
      let _this = this.$refs.PrintOnly;
      _this.visible = true;
      _this.orderNumber = this.form.number;
      _this.getPrint();
    }
  }
}
